package com.fll.protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 *
 *
 * 编码器
 *
 * @author fanlei
 * @version 1.0
 * @date 2019年01月25日
 */
public class ProxyMessageEncoder extends MessageToByteEncoder<ProxyMessage> {

    private static final int TYPE_SIZE = 1;
    private static final int SERIAL_NUMBER_SIZE = 8;
    private static final int URI_LENGTH_SIZE = 1;

    public ProxyMessageEncoder() {
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, ProxyMessage msg, ByteBuf out) throws Exception {
        int bodyLength = 10;
        byte[] uriBytes = null;

        if (msg.getUri() != null) {
            uriBytes = msg.getUri().getBytes();
            bodyLength += uriBytes.length;
        }

        if (msg.getData() != null) {
            bodyLength += msg.getData().length;
        }

        //数据长度
        out.writeInt(bodyLength);
        //消息类型
        out.writeByte(msg.getType());
        //
        out.writeLong(msg.getSerialNumber());
        if (uriBytes != null) {
            //uri长度
            out.writeByte((byte)uriBytes.length);
            //uri数据
            out.writeBytes(uriBytes);
        } else {
            out.writeByte(0);
        }

        //数据
        if (msg.getData() != null) {
            out.writeBytes(msg.getData());
        }


    }

}
